import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
import { Orders } from "../entity/Orders";
import { User } from "../entity/User";
import { Product } from "../entity/Product";
import { auth as Auth } from "../../utils/auth";
import { encrypt, decrypt } from "../../utils/crypto";
@Controller("/api/order")
export class CarouselController {
	@Get("/list")
	async getOrder(ctx: BaseContext) {
		try {
			const ordersRepository = getRepository(Orders)
			const userRepository = getRepository(User)
			const productRepository = getRepository(Product)
			let ordersList = await ordersRepository.find()
			const userList = await userRepository.find()
			const productList = await productRepository.find()
			let newList = ordersList.map(item => {
				return {
					...item,
					user_name: userList.find((user) => Number(user.user_id) == Number(item.user_id))?.userName,
					product_name: productList.find((user) => Number(user.product_id) == Number(item.product_id))?.product_name
				}
			})
			ctx.body = {
				...Exception(200, "查询成功"),
				data: newList,
			}
		} catch (error) {
			ctx.body = Exception(112, "查询失败");
		}
	}

	@Post('/del')
	async delOrder(ctx: BaseContext) {
		try {
			const { id } = ctx.request.body;
			if (!id) {
				return ctx.body = Exception(112, "id不能为空")
			}
			const ordersRepository = getRepository(Orders)
			const orders = await ordersRepository.findOne(id)
			if (!orders) return ctx.body = Exception(112, "id不存在");
			await ordersRepository.remove(orders)
			ctx.body = Exception(200, "删除成功");
		} catch (error) {
			ctx.body = Exception(112, "删除失败");
		}
	}
}
